package com.yu.crm.ws.pw;


import com.yu.crm.ws.WsMessage;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.JsonHelpers;

import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 模块名称：WS管理类
 * 功能说明：前端地址样式  ws://127.0.0.1:8084/websocketpw/{sid}
 *
 * @Author: bin-donnie
 * @Date: 2019/7/4 5:45 PM
 */


@Log4j2
public class WebSocketManagerPW {

    interface IMessageHandler {
        void onOpen();

        void onMessage(WsMessage wsMessage);

        void onClose();
    }

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<WebSocketClientPW> clientSet = new CopyOnWriteArraySet<>();

    //接收消息句柄
    private static IMessageHandler messageHandler = null;

    public static void addClient(WebSocketClientPW client) {
        clientSet.add(client);
    }

    public static void removeClient(WebSocketClientPW client) {
        clientSet.remove(client);
    }

    public static synchronized int getOnlineCount() {
        return clientSet.size();
    }

    public static void registerOnMessage(IMessageHandler handler) {
        messageHandler = handler;
    }

    public static void unRegisterOnMessage(IMessageHandler handler) {
        messageHandler = null;
    }

    /**
     * 单发消息
     *
     * @param wsMessage
     * @param receiverId
     */
    public static void sendMessage(WsMessage wsMessage, String receiverId) {
        for (WebSocketClientPW client : clientSet) {
            if (DataHelpers.isNotEmpty(client.getSid()) && client.getSid().equals(receiverId)) {
                try {
                    wsMessage.setReceiverId(receiverId);
                    String json = JsonHelpers.toJson(wsMessage).get();
                    client.getSession().getBasicRemote().sendText(json);
                    log.info("WS 发送消息:{}, sid={}", json, receiverId);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.info("WS 发送失败:{}, sid={}, error={}", wsMessage.getContent(), receiverId, e.getMessage());
                }
            }
        }
    }

    /**
     * 群发消息
     *
     * @param wsMessage
     */
    public static void sendMessage(WsMessage wsMessage) {
        for (WebSocketClientPW client : clientSet) {
            try {
                wsMessage.setReceiverId(client.getSid());
                String json = JsonHelpers.toJson(wsMessage).get();
                client.getSession().getBasicRemote().sendText(json);
                log.info("WS 发送消息:{}", json);
            } catch (IOException e) {
                e.printStackTrace();
                log.info("WS 发送失败:{}, error={}", wsMessage.getContent(), e.getMessage());
            }
        }
    }

    public static void onOpen() {
        if (messageHandler != null) {
            messageHandler.onOpen();
        }
    }

    /**
     * 接收消息
     *
     * @param wsMessage
     */
    public static void onMessage(WsMessage wsMessage) {
        if (messageHandler != null) {
            messageHandler.onMessage(wsMessage);
        }
    }

    public static void onClose() {
        if (messageHandler != null) {
            messageHandler.onClose();
        }
    }
}
